#pragma once

#include <glew.h>
#include <vector>
#include <glm/glm.hpp>
using namespace std;

class Mesh {
public:
	GLuint VBO, VAO;
	GLuint count;
	vector<glm::vec3> positions;
	vector<glm::vec2> texcoords;
	vector<glm::vec3> normals;

	Mesh(const vector<glm::vec3> positions, const vector<glm::vec2> texcoords, const vector<glm::vec3> normals):
		positions(positions),texcoords(texcoords),normals(normals) {
		count = positions.size();
		bindData();
	}

	void bindData() {
		glGenVertexArrays(1, &VAO);
		glBindVertexArray(VAO);

		glGenBuffers(1, &VBO);
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * (positions.size() + normals.size()) + sizeof(glm::vec2) * texcoords.size(), NULL, GL_STATIC_DRAW);

		//将数据传入缓冲区
		GLuint size_pos = sizeof(glm::vec3) * positions.size();
		GLuint size_texcoord = sizeof(glm::vec2) * texcoords.size();
		GLuint size_normal = sizeof(glm::vec3) * normals.size();
		GLuint offset_pos = 0;
		GLuint offset_texcoord = size_pos;
		GLuint offset_normal = size_pos + size_texcoord;
		glBufferSubData(GL_ARRAY_BUFFER, offset_pos, size_pos, positions.data());
		glBufferSubData(GL_ARRAY_BUFFER, offset_texcoord, size_texcoord, texcoords.data());
		glBufferSubData(GL_ARRAY_BUFFER, offset_normal, size_normal, normals.data());

		//关联缓冲区的数据和着色器中的顶点属性
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const void*)offset_pos);
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (const void*)offset_texcoord);
		glEnableVertexAttribArray(2);
		glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (const void*)offset_normal);

		glBindVertexArray(0);
	}

	void draw(GLuint programId) {
		glUseProgram(programId);
		glBindVertexArray(VAO);
		glDrawArrays(GL_TRIANGLES, 0, count);
		glBindVertexArray(0);
	}
};
